package neo4j.util;

import java.io.File;
import java.io.IOException;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.DefaultFileSystemAbstraction;
import org.neo4j.kernel.StoreLocker;

public class Neo4jUtil
{
	public static GraphDatabaseService startService(String DB_PATH)
	{
		GraphDatabaseService graphDbService = new GraphDatabaseFactory()
				.newEmbeddedDatabase(DB_PATH);
		registerShutdownHook(graphDbService);
		return graphDbService;
	}

	public static void releaseLock(String dbPath)
	{
		StoreLocker lock = new StoreLocker(new DefaultFileSystemAbstraction());
		lock.checkLock(new File(dbPath));
		try
		{
			lock.release();
		}
		catch (IOException e1)
		{
			e1.printStackTrace();
		}
	}

	/**
	 * Registers a shutdown hook for the Neo4j instance so that it shuts down
	 * nicely when the VM exits (even if you "Ctrl-C" the running application).
	 * 
	 * @param graphDb
	 */
	private static void registerShutdownHook(final GraphDatabaseService graphDb)
	{
		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			@Override
			public void run()
			{
				graphDb.shutdown();
			}
		});
	}
}
